import JSEncrypt from 'jsencrypt'

// 通用请求处理函数
async function request(url, options = {}) {
  try {
    const token = localStorage.getItem('token')
    const headers = {
      'Content-Type': 'application/json',
      ...options.headers
    }

    // 如果有token，添加到请求头
    if (token && !url.includes('/login') && !url.includes('/publicKey')) {
      headers['Authorization'] = `Bearer ${token}`
    }

    const response = await fetch(url, {
      headers,
      ...options
    })

    const data = await response.json()

    // 处理新的API响应格式
    if (!response.ok) {
      throw new Error(data.message || `请求失败: ${response.status}`)
    }

    // 如果是统一响应格式，返回data字段
    if (data.code !== undefined) {
      if (data.code !== 200) {
        throw new Error(data.message || '请求失败')
      }
      return data.data || data
    }

    return data
  } catch (error) {
    if (error.name === 'TypeError' && error.message.includes('fetch')) {
      throw new Error('网络连接失败，请检查网络设置')
    }
    throw error
  }
}

// 获取RSA公钥
export async function getPublicKey() {
  try {
    const response = await fetch('/api/publicKey')
    if (!response.ok) {
      throw new Error('获取公钥失败')
    }
    return await response.text()
  } catch (error) {
    throw new Error('获取公钥失败，请稍后重试')
  }
}

// 登录接口
export async function login(username, password) {
  // 参数验证
  if (!username || !password) {
    throw new Error('用户名和密码不能为空')
  }

  if (username.length < 3) {
    throw new Error('用户名长度不能少于3位')
  }

  if (password.length < 6) {
    throw new Error('密码长度不能少于6位')
  }

  try {
    // 获取公钥
    const publicKey = await getPublicKey()

    // 用公钥加密密码
    const encrypt = new JSEncrypt()
    encrypt.setPublicKey(`-----BEGIN PUBLIC KEY-----\n${publicKey}\n-----END PUBLIC KEY-----`)
    const encryptedPwd = encrypt.encrypt(password)

    if (!encryptedPwd) {
      throw new Error('密码加密失败，请稍后重试')
    }

    // 发送登录请求
    const result = await request('/api/login', {
      method: 'POST',
      body: JSON.stringify({
        username: username.trim(),
        password: encryptedPwd
      })
    })

    return result
  } catch (error) {
    throw error
  }
}

// 验证Token有效性
export async function validateToken(token) {
  try {
    return await request('/api/validate-token', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
  } catch (error) {
    throw new Error('Token验证失败')
  }
}

// 退出登录
export async function logout() {
  try {
    const token = localStorage.getItem('token')
    if (token) {
      await request('/api/logout', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })
    }
  } catch (error) {
    console.warn('退出登录请求失败:', error.message)
  } finally {
    // 无论请求是否成功，都清除本地存储
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
  }
}